package org.management.web.controller;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.management.base.data.Result;
import org.management.config.shiro.manager.TokenManager;
import org.management.system.entity.ResourceEntity;
import org.management.system.entity.RoleEntity;
import org.management.system.entity.UserEntity;
import org.management.system.service.ResourceService;
import org.management.system.service.RoleService;
import org.management.utils.EncryptUtils;
import org.management.utils.WebUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class WebController {

	@Resource
	private ResourceService resourceService;

	@Resource
	private RoleService roleService;

	@PostMapping(value = "login")
	@ApiOperation("用户登录")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "name",value = "用户登录名称",required = true),
			@ApiImplicitParam(name = "password",value = "用户登录密码",required = true)
	})
	public Result login(@NotEmpty(message = "登录名称不能为空") String userName,
	                    @NotEmpty(message = "用户密码不能为空") String password) {
		password = EncryptUtils.decryptRsaPassword(password);
		UserEntity user = new UserEntity();
		user.setLoginName(userName);
		user.setPassword(password);
		user = TokenManager.login(user,false);
		String token = EncryptUtils.encryptRsaPassword(TokenManager.getSessionId());
		String ip = WebUtils.getLocalHostAddress().toString();
		ip = EncryptUtils.encryptRsaPassword(ip);
		List<ResourceEntity> resources = resourceService.loadUserResources();
		List<RoleEntity> roles = roleService.getRoleByUserId(user.getId());
		Map<String, Object> objectMap = new HashMap<>();
		objectMap.put("user", user);
		objectMap.put("roles", roles);
		objectMap.put("token", token);
		objectMap.put("address", ip);
		objectMap.put("resources", resources);
		return Result.success("登录成功",objectMap);
	}

	@PostMapping(value = "logout")
	@ApiOperation("当前用户退出")
	public Result logout() {
		TokenManager.logout();
		return Result.success("退出成功");
	}

	@GetMapping(value = "public/key")
	public Result getPublicKey() {
		String key = EncryptUtils.getPublicKey();
		return Result.success("获取公钥成功", key);
	}
}
